package com.school.controller.user;

import com.school.service.UserService;
import com.school.service.impl.UserServiceImpl;
import com.school.util.ResponseJsonUtil;
import com.school.vo.R;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/signin")
public class SignInController extends HttpServlet {

    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (username == null){
            ResponseJsonUtil.write(resp, R.err("用户名不能为空"));
            return;
        }
        if (password == null){
            ResponseJsonUtil.write(resp, R.err("密码不能为空"));
            return;
        }
        // 其他判断：长度
        Integer id = userService.signIn(username,password);
        if (id != null){
            // 怎么存：键(用户名)值(标识)对
            ServletContext context = getServletContext();
            String token = UUID.randomUUID().toString(); // 686195bb-b983-4615-93a7-3c2441e9cf31
            String value = UUID.randomUUID().toString().concat(UUID.randomUUID().toString());
            // 存token
            context.setAttribute(token, value);
            // 存用户id
            // context.setAttribute(username,id);
            // context.setAttribute(token,id);
            context.setAttribute(value,id);
            // 将标识返回给前端
            R result = R.ok("登录成功", 1);
            result.put("token", token);
            ResponseJsonUtil.write(resp, result);
        }else {
            ResponseJsonUtil.write(resp, R.err("登录失败"));
        }
    }
}
